<?php

namespace system\components;

use system\core\Document;
use system\libs\utils\Utils;
/**
 * Base class for all {@link DocumentComponent}
 * holds all data that will be transformed to xml data
 * structure which will be represented visually using
 * XSL template associated with this component. Every
 * public variable will be transformed into XML tag.
 *
 * There two reserved variables names used as meta data
 * for concrete component: __componentName - holds name of concrete 
 * {@link DocumentComponent} and will be used as name for "root"
 * of this element
 *
 * __inner - holds array of {@link DocumentComponent}'s that will be processed
 * in a same way as this one
 *
 * @package system\components
 * @author Pavel Egorov {@link mailto:pavel@egorov.ru pavel@egorov.ru}
 * @version 0.0.1 $Revision: 50 $
 * @copyright Copyright (c) 2011, Pavel Egorov
 */
class DocumentComponent implements Component{


    /**
     * Adds another page component and associates or not template
     *
     * @param DocumentComponent $component component to be added
     */
    public function add(Component $component,$templateName = NULL) {
        $this->__inner[] = $component;
        if($templateName != NULL){
            Document::getInstance()->addViewItem($templateName);
        }
    }

    public function toXML(\DOMDocument $doc) {
        $element = $doc->createElement(Utils::classNameFromFullName(get_class($this)));
        self::arrayToXML($doc, get_object_vars($this), $element);
        return $element;
    }

    private static final function arrayToXML(\DOMDocument $doc, $array, \DOMElement $parent){
        foreach($array as $key => $value){
            if($value instanceof Component){
                $parent->appendChild($value->toXML($doc));
            }else if(is_array($value)){
                if(!is_int($key) && $key != "__inner"){
                    $element = $doc->createElement($key);
                    $parent->appendChild($element);
                    self::arrayToXML($doc, $value, $element);
                }else{
                    self::arrayToXML($doc, $value, $parent);
                }
            }else{
                if(!empty ($value)){
                    $element = $doc->createElement($key);
                    $element->appendChild($doc->createTextNode($value));
                    $parent->appendChild($element);
                }
            }
        }
    }
}